import {useParams} from "react-router-dom";
import {getQuestionsService} from "../services/question";
import {useRequest} from "ahooks";
import {useEffect} from "react";
import {useDispatch} from "react-redux";
import {resetComponents} from "../store/componentsReducer";

function useLoadQuestionData() {
    const {id = ''} = useParams()

    const dispatch = useDispatch()

    const {data, loading, error, run} = useRequest(
        async (id: string) => {
            if (!id) {
                throw new Error('id is required')
            }
            const data = await getQuestionsService(id)
            return data
        }, {
            manual: true,
        });

    //根据获取的data 色值 redux store
    useEffect(() => {
        if (!data) {
            return
        }
        const {title = '', componentList = []} = data
        dispatch(resetComponents({componentList}))
    }, [data])


    useEffect(() => {
        run(id)
    }, [id])
    return {loading, error}
}

export default useLoadQuestionData